<script setup>
import { computed, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addStudentService,
  listStudentService,
  updateStudentService,
} from "@/api/student.js";
import { queryLikeCollegeByCollegeNameService } from "@/api/college.js";
import { queryMajorByCollegeNameService } from "@/api/major.js";
import { queryClassByMajorNameService } from "@/api/classes.js";
import { getAllCategoriesService } from "@/api/readcategories.js";
import { deleteUserService } from "@/api/user.js";

const studentsData = ref([]);
const pageNum = ref(1);
const pageSize = ref(15);
const total = ref(10);
const showAddDialog = ref(false);
const showUpdateDialog = ref(false);
const collegeNameSuggestions = ref([]);
const majorNameSuggestions = ref([]);
const classNameSuggestions = ref([]);
const addFormRef = ref(null);
const updateFormRef = ref(null);
const selectedStudents = ref([]);

let isDialogOpen = false; // 用于控制 watch 的执行

const newStudent = ref({
  studentId: "",
  username: "",
  passwordModified: false,
  password: "",
  studentName: "",
  status: "",
  collegeName: "",
  majorName: "",
  className: "",
  classId: "",
  categoryId: "",
  categoryName: "",
});

const searchStudent = ref({
  studentId: "",
  userId: "",
  username: "",
  password: "",
  studentName: "",
  status: "",
  collegeName: "",
  majorName: "",
  className: "",
  categoryId: "",
  categoryName: "",
});

const handleSizeChange = (size) => {
  pageSize.value = size;
  listStudents();
};

const handleCurrentChange = (num) => {
  pageNum.value = num;
  listStudents();
};

const listStudents = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchStudent.value,
  };
  let result = await listStudentService(params);
  total.value = result.data.total;
  studentsData.value = result.data.records;
};

const reset = async () => {
  searchStudent.value = {
    studentId: "",
    userId: "",
    username: "",
    password: "",
    studentName: "",
    status: "",
    collegeName: "",
    majorName: "",
    className: "",
    categoryId: "",
    categoryName: "",
  };
  await listStudents();
};

const addStudent = async () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log("newStudent", newStudent);
      let addResult = await addStudentService(newStudent.value);
      if (addResult.code === 0) {
        showAddDialog.value = false;
        ElMessage.success("新增成功");
        await listStudents();
      } else {
        ElMessage.error(addResult.message);
      }
    }
  });
};

const updateStudent = async () => {
  updateFormRef.value.validate(async (valid) => {
    if (valid) {
      const studentData = { ...newStudent.value };
      if (!newStudent.value.passwordModified) {
        delete studentData.password; // 如果密码未修改，则删除密码字段
      }
      console.log("studentData", studentData);
      let updateResult = await updateStudentService(studentData);
      if (updateResult.code === 0) {
        showUpdateDialog.value = false;
        ElMessage.success("更新成功");
        await listStudents();
      } else {
        ElMessage.error(updateResult.message);
      }
    }
  });
};

const deleteStudent = async (userId) => {
  await ElMessageBox.confirm("此操作将永久删除该学生, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  let deleteResult = await deleteUserService(userId);
  if (deleteResult.code === 0) {
    ElMessage.success("删除成功");
    await listStudents();
  } else {
    ElMessage.error(deleteResult.message);
  }
};

const confirmDelete = (userId) => {
  ElMessageBox.confirm("此操作将永久删除该学生, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteStudent(userId);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSelectionChange = (selection) => {
  selectedStudents.value = selection;
};

const confirmBatchDelete = () => {
  ElMessageBox.confirm("此操作将永久删除选中的学生, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      for (const student of selectedStudents.value) {
        await deleteUserService(student.userId);
      }
      ElMessage.success("批量删除成功");
      await listStudents();
    })
    .catch(() => {
      ElMessage.info("已取消批量删除");
    });
};

const confirmResetPasswords = () => {
  ElMessageBox.confirm(
    "此操作将重置选中的学生密码为: 123456, 是否继续?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  )
    .then(async () => {
      for (const student of selectedStudents.value) {
        student.password = "123456";
        await updateStudentService(student);
      }
      ElMessage.success("批量重置密码成功");
      await listStudents();
    })
    .catch(() => {
      ElMessage.info("已取消重置密码");
    });
};

const confirmResetOnePassword = (student) => {
  ElMessageBox.confirm(
    "此操作将重置选中的学生密码为: 123456, 是否继续?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  )
    .then(async () => {
      student.password = "123456";
      let updateResult = await updateStudentService(student);
      if (updateResult.code === 0) {
        ElMessage.success("更新成功");
        await listStudents();
      } else {
        ElMessage.error(updateResult.message);
      }
    })
    .catch(() => {
      ElMessage.info("已取消重置密码");
    });
};

const viewUpdate = async (row) => {
  isDialogOpen = true;
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
  collegeNameSuggestions.value = [];
  majorNameSuggestions.value = [];
  classNameSuggestions.value = [];
  newStudent.value = { ...row };
  newStudent.value.passwordModified = false;
  showUpdateDialog.value = true;
  isDialogOpen = false;
};

const viewAdd = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  newStudent.value = {
    studentId: "",
    username: "",
    password: "123456",
    studentName: "",
    status: "",
    collegeName: "",
    majorName: "",
    className: "",
    classId: "",
    categoryId: "",
  };
  showAddDialog.value = true;
};

const queryCollegeNameByCollegeName = async (queryString, cb) => {
  try {
    const result = await queryLikeCollegeByCollegeNameService(queryString);
    if (result.code === 0) {
      collegeNameSuggestions.value = result.data.map((college) => ({
        value: college.collegeName,
      }));
      if (collegeNameSuggestions.value.length === 0) {
        ElMessage.error(
          "未匹配到正确的学院名，请输入正确的学院名或先插入新的学院信息",
        );
      } else if (collegeNameSuggestions.value.length === 1) {
        handleCollegeChange(collegeNameSuggestions.value[0]);
      }
      cb(collegeNameSuggestions.value);
    } else {
      console.error(result.message);
    }
  } catch (error) {
    console.error(error);
  }
};

const queryMajorNameByCollegeName = async (queryString, cb) => {
  try {
    const result = await queryMajorByCollegeNameService(
      newStudent.value.collegeName,
      queryString,
    );
    if (result.code === 0) {
      majorNameSuggestions.value = result.data.map((major) => ({
        value: major.majorName,
      }));
      if (majorNameSuggestions.value.length === 0) {
        ElMessage.error(
          "未匹配到正确的专业名，请输入正确的专业名或检查学院信息",
        );
      } else if (majorNameSuggestions.value.length === 1) {
        handleMajorChange(majorNameSuggestions.value[0]);
      }
      cb(majorNameSuggestions.value);
    } else {
      console.error(result.message);
    }
  } catch (error) {
    console.error(error);
  }
};

const queryClassNameByMajorName = async (queryString, cb) => {
  try {
    const result = await queryClassByMajorNameService(
      newStudent.value.majorName,
      queryString,
    );
    if (result.code === 0) {
      classNameSuggestions.value = result.data.map((cls) => ({
        value: cls.className,
      }));
      if (classNameSuggestions.value.length === 0) {
        ElMessage.error(
          "未匹配到正确的班级名，请输入正确的班级名或检查专业信息",
        );
      } else if (classNameSuggestions.value.length === 1) {
        handleClassChange(classNameSuggestions.value[0]);
      }
      cb(classNameSuggestions.value);
    } else {
      console.error(result.message);
    }
  } catch (error) {
    console.error(error);
  }
};

watch(
  () => newStudent.value.collegeName,
  async (newVal, oldVal) => {
    if (isDialogOpen && newVal !== oldVal && newVal.length > 0) {
      newStudent.value.majorName = "";
      newStudent.value.className = "";
    }
  },
);

watch(
  () => newStudent.value.majorName,
  async (newVal, oldVal) => {
    if (isDialogOpen && newVal !== oldVal && newVal.length > 0) {
      newStudent.value.className = "";
    }
  },
);

const handleCollegeChange = (item) => {
  newStudent.value.collegeName = item.value;
  newStudent.value.majorName = "";
  newStudent.value.className = "";
};

const handleMajorChange = (item) => {
  newStudent.value.majorName = item.value;
  newStudent.value.className = "";
};

const handleClassChange = (item) => {
  newStudent.value.className = item.value;
};

const statusCellStyle = ({ row, column }) => {
  if (column.property === "status") {
    switch (row.status) {
      case "可借阅":
        return { backgroundColor: "rgba(133, 206, 97, 0.3)" };
      case "借阅受限":
        return { backgroundColor: "rgba(247, 137, 137, 0.3)" };
      default:
        return { backgroundColor: "rgba(235, 181, 99, 0.3)" };
    }
  }
};

const rules = {
  studentName: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
  categoryId: [
    { required: true, message: "请选择读者类别", trigger: "change" },
  ],
  collegeName: [{ required: true, message: "请输入学院名", trigger: "blur" }],
  majorName: [{ required: true, message: "请输入专业名", trigger: "blur" }],
  className: [{ required: true, message: "请输入班级名", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};

const categories = ref([]);

// 获取所有类别
const fetchCategories = async () => {
  try {
    const result = await getAllCategoriesService();
    if (result.code === 0) {
      categories.value = result.data;
    } else {
      ElMessage.error("获取类别失败");
    }
  } catch (error) {
    console.error("获取类别时出错：", error);
    ElMessage.error("获取类别时出现错误");
  }
};

const filteredCategories = computed(() => {
  return categories.value.filter(
    (category) => category.categoryName !== "教师",
  );
});

fetchCategories();
listStudents();
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="searchStudent.studentId"
      placeholder="请输入学生ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchStudent.studentName"
      placeholder="请输入学生姓名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchStudent.collegeName"
      placeholder="请输入学院名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchStudent.majorName"
      placeholder="请输入专业名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchStudent.className"
      placeholder="请输入班级名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchStudent.userId"
      placeholder="请输入关联用户ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchStudent.categoryName"
      placeholder="请输入读者类别"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchStudent.username"
      placeholder="请输入用户名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchStudent.status"
      placeholder="请输入借阅状态"
      clearable
      class="search-input"
    />
  </div>
  <div class="button-group">
    <div class="extra-buttons">
      <el-button
        type="danger"
        @click="confirmBatchDelete"
        :disabled="selectedStudents.length === 0"
        icon="RemoveFilled"
      >
        批量删除
      </el-button>
      <el-button
        type="warning"
        @click="confirmResetPasswords"
        :disabled="selectedStudents.length === 0"
        icon="RefreshLeft"
      >
        批量重置密码
      </el-button>
    </div>
    <el-button @click="listStudents" type="primary" icon="Search"
      >搜索</el-button
    >
    <el-button @click="reset" type="warning" icon="RefreshRight"
      >重置</el-button
    >
    <el-button type="success" @click="viewAdd" icon="CirclePlus"
      >新增学生</el-button
    >
  </div>

  <el-table
    :data="studentsData"
    :cell-style="statusCellStyle"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="40" />
    <el-table-column
      fixed
      sortable
      prop="studentId"
      label="学生ID"
      width="100"
    />
    <el-table-column sortable prop="studentName" label="学生姓名" width="120" />
    <el-table-column
      sortable
      prop="collegeName"
      label="学院"
      width="110"
    />
    <el-table-column sortable prop="majorName" label="专业" min-width="90" />
    <el-table-column sortable prop="className" label="班级" min-width="90" />
    <el-table-column sortable prop="userId" label="用户ID" min- width="100" />
    <el-table-column
      sortable
      prop="categoryName"
      label="读者类别"
      min-width="130"
      :filters="[
        { text: '非教研人员', value: '非教研人员' },
        { text: '博士研究生', value: '博士研究生' },
        { text: '硕士研究生', value: '硕士研究生' },
        { text: '本科生', value: '本科生' },
        { text: '专科生', value: '专科生' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column sortable prop="username" label="用户名" min-width="100" />
    <el-table-column sortable prop="password" label="密码" min-width="140" />
    <el-table-column sortable prop="email" label="邮箱" min-width="140" />
    <el-table-column
      sortable
      prop="status"
      label="状态"
      min-width="100"
      :filters="[
        { text: '可借阅', value: '可借阅' },
        { text: '借阅受限', value: '借阅受限' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column label="操作" align="center" fixed="right" width="330">
      <template #default="scope">
        <el-button type="warning" @click="viewUpdate(scope.row)" icon="Refresh"
          >更新</el-button
        >
        <el-button
          type="danger"
          @click="confirmDelete(scope.row.userId)"
          icon="delete"
          >删除</el-button
        >
        <el-button
          type="info"
          @click="confirmResetOnePassword(scope.row)"
          icon="Key"
          >重置密码</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-end"
  />

  <el-dialog title="新增学生" v-model="showAddDialog" width="500">
    <el-form :model="newStudent" :rules="rules" ref="addFormRef">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input v-model="newStudent.studentName"></el-input>
      </el-form-item>
      <el-form-item label="读者类别" prop="categoryId">
        <el-select v-model="newStudent.categoryId" placeholder="请选择读者类别">
          <el-option
            v-for="category in filteredCategories"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="collegeName">
        <el-autocomplete
          v-model="newStudent.collegeName"
          :fetch-suggestions="queryCollegeNameByCollegeName"
          placeholder="请输入学院名"
          @select="handleCollegeChange"
        />
      </el-form-item>
      <el-form-item label="专业" prop="majorName">
        <el-autocomplete
          v-model="newStudent.majorName"
          :disabled="!newStudent.collegeName"
          :fetch-suggestions="queryMajorNameByCollegeName"
          placeholder="请输入专业名"
          @select="handleMajorChange"
        />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-autocomplete
          v-model="newStudent.className"
          :disabled="!newStudent.collegeName || !newStudent.majorName"
          :fetch-suggestions="queryClassNameByMajorName"
          placeholder="请输入班级名"
          @select="handleClassChange"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="newStudent.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="newStudent.password"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="newStudent.status">
          <el-radio :label="'可借阅'">可借阅</el-radio>
          <el-radio :label="'借阅受限'">借阅受限</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="addStudent()">确定</el-button>
    </span>
  </el-dialog>

  <el-dialog title="更新学生信息" v-model="showUpdateDialog" width="500">
    <el-form :model="newStudent" :rules="rules" ref="updateFormRef">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input v-model="newStudent.studentName"></el-input>
      </el-form-item>
      <el-form-item label="读者类别" prop="categoryId">
        <el-select v-model="newStudent.categoryId" placeholder="请选择读者类别">
          <el-option
            v-for="category in filteredCategories"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="collegeName">
        <el-autocomplete
          v-model="newStudent.collegeName"
          :fetch-suggestions="queryCollegeNameByCollegeName"
          placeholder="请输入学院名"
          @select="handleCollegeChange"
        />
      </el-form-item>
      <el-form-item label="专业" prop="majorName">
        <el-autocomplete
          v-model="newStudent.majorName"
          :fetch-suggestions="queryMajorNameByCollegeName"
          placeholder="请输入专业名"
          @select="handleMajorChange"
        />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-autocomplete
          v-model="newStudent.className"
          :fetch-suggestions="queryClassNameByMajorName"
          placeholder="请输入班级名"
          @select="handleClassChange"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="newStudent.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="newStudent.password"
          @input="newStudent.passwordModified = true"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="newStudent.status">
          <el-radio value="可借阅">可借阅</el-radio>
          <el-radio value="借阅受限">借阅受限</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showUpdateDialog = false">取消</el-button>
      <el-button type="primary" @click="updateStudent">确定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped>
.button-group {
  display: flex;
  gap: 5px;
  justify-content: flex-end;
  margin-bottom: 10px;
}
</style>
